<script setup>
import router from '@/router'
import { ElMessage } from 'element-plus'
import { ref, nextTick, onMounted } from 'vue'

const count = ref(0)

// 当前输入的消息
const message = ref('')

// 聊天记录列表：{ type: 'req' | 'res', text: string }
const chatList = ref([])

// 获取 textarea 和滚动容器的引用
const textareaRef = ref(null)
const scrollbarRef = ref(null) // 需要给 el-scrollbar 加 ref

// 自动调整高度
const autoResize = () => {
  const el = textareaRef.value
  if (!el) return
  el.style.height = 'auto'
  const maxHeight = 150
  const newHeight = Math.min(el.scrollHeight, maxHeight)
  el.style.height = `${newHeight}px`
}

// 发送消息
const sendMessage = () => {
  count.value++

  const text = message.value?.trim()
  if (!text) return

  // 添加用户消息
  chatList.value.push({ type: 'req', text })

  // 清空输入框并恢复输入框状态
  message.value = ''
  nextTick(() => {
    autoResize()
    textareaRef.value?.focus()
  })
    if (count.value > 1) {
    // 模拟 AI 逐字输出（在关键句前换行并加粗）
    const replyHTML = `正在进行跳转，请稍等...`
    const aiMsg = { type: 'res', text: '', html: '' }
    chatList.value.push(aiMsg)
    scrollToBottom()

    let index = 0
    const speed = 60 // 每 30ms 输出一个字符
    const timer = setInterval(() => {
      if (index >= replyHTML.length) {
        clearInterval(timer)
        return
      }
      aiMsg.html += replyHTML[index]
      // 触发响应式更新
      chatList.value = [...chatList.value]
      scrollToBottom()
      index++
    }, speed)
    setTimeout(() => {
      router.push('/user/profile/base')
      ElMessage.success('跳转成功')
    }, 1500)
    return
  }
  // 模拟 AI 逐字输出（在关键句前换行并加粗）
  const replyHTML = `2025级计算机应用技术1班整体心理健康状况趋于平稳，
  多数学生能较好适应学习生活节奏，
  情绪调节能力和人际交往状态良好。
  从评估数据来看，
  班级内大部分同学心理状态处于健康区间，
  其中5人处于轻度焦虑正常水平，
  该群体主要因课程压力、
  未来职业规划产生短暂情绪波动，
  通过常规心理疏导即可缓解；
  目前班级心理预警系统共标记预警1人，
  主要表现为情绪低落频率略高，
  需通过定期谈心及时干预；
  同时确定需重点关注1人，
  其在人际关系与学业适应上存在较明显困扰，
  需联合辅导员、心理老师制定个性化帮扶方案。整体而言，班级心理风险可控，后续需持续关注重点人群，
  并强化班级心理支持氛围建设。<br/><strong style="font-size: 16px">需要查看需重点关注的学生的心理档案吗？</strong>`
  const aiMsg = { type: 'res', text: '', html: '' }
  chatList.value.push(aiMsg)
  scrollToBottom()

  let index = 0
  const speed = 10 // 每 30ms 输出一个字符
  const timer = setInterval(() => {
    if (index >= replyHTML.length) {
      clearInterval(timer)
      return
    }
    aiMsg.html += replyHTML[index]
    // 触发响应式更新
    chatList.value = [...chatList.value]
    scrollToBottom()
    index++
  }, speed)
}

// 绑定回车发送
const handleKeydown = (e) => {
  if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.altKey) {
    e.preventDefault()
    sendMessage()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const scrollEl = document.querySelector('.el-scrollbar__wrap')
    if (scrollEl) {
      scrollEl.scrollTop = scrollEl.scrollHeight
    }
  })
}

// 开启新对话
const startNewChat = () => {
  chatList.value = []
  message.value = ''
  textareaRef.value?.focus()
}

// 控制小机器人的消失
const isHidden = ref(false)

// 页面加载后自动聚焦输入框
onMounted(() => {
  textareaRef.value?.focus()
})
</script>

<template>
  <!-- 滚动区域：聊天内容 -->
  <el-scrollbar ref="scrollbarRef" height="60vh">
    <h2 style="color: #1475fb">AI心理分析</h2>
    <p style="color: rgba(0, 0, 0, 0.5); font-size: 14px; padding: 10px 0">
      我可以帮你解答学习疑惑，也会提供陪伴和支持😊
    </p>

    <!-- 资源推荐 -->
    <div class="recommend-box">
      <div>
        <div style="font-size: 14px; font-weight: 600">资源推荐</div>
        <div style="font-size: 12px; color: rgba(0, 0, 0, 0.5)">海量优质资源，一键送达</div>
      </div>
      <div class="recommend-img"></div>
    </div>

    <!-- 聊天消息列表 -->
    <div
        v-for="(item, index) in chatList"
        :key="index"
        :class="['message-box', item.type === 'req' ? 'req-box' : 'res-box']"
    >
      <div v-if="item.type === 'res'" class="ai-avatar"></div>
      <div v-if="item.type === 'req'" class="req">{{ item.text }}</div>
      <div v-else class="res"><span v-html="item.html || item.text"></span></div>
      <div v-if="item.type === 'req'" class="user-avatar"></div>
    </div>
  </el-scrollbar>

  <!-- 输入框区域 -->
  <div class="input-box">
    <!-- 开启新对话按钮 -->
    <div class="open-new-box" @click="startNewChat">
      <img id="img1" src="@/assets/images/AI/assistant/新建对话.png" alt="" width="20px" height="20px" />
      <img id="img2" src="@/assets/images/AI/assistant/新建对话-触发.png" alt="" width="0" height="0" />
      开启新对话
    </div>

    <!-- 输入框 -->
    <textarea
        ref="textareaRef"
        v-model="message"
        placeholder="请输入您的问题"
        @input="autoResize"
        @keydown="handleKeydown"
    ></textarea>

    <!-- 发送按钮区域 -->
    <div style="display: flex; justify-content: right; align-items: center">
      <sapn style="color: rgba(0, 0, 0, 0.3);font-size: 12px">shift+enter换行，enter发送</sapn>
      <el-button type="primary" round style="margin-left: 10px" @click="sendMessage" :disabled="!message">
        <el-icon><Promotion /></el-icon>发送
      </el-button>
    </div>

    <!-- 小机器人区域 -->
    <div :class="['robot-box', { 'hidden': isHidden }]" @click="isHidden = true"></div>
  </div>
</template>

<style scoped>
.ai-avatar {
  width: 60px;
  height: 50px;
  border-radius: 50%;
  background: url('@/assets/images/AI/assistant/AI头.png') center center / 100% 100% no-repeat;
}
.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 20px;
  margin-left: 15px;
  background: url('@/assets/images/AI/assistant/用户头像.png') center center / 60% 60% no-repeat;
}
/* 聊天消息通用样式 */
.message-box {
  display: flex;
  margin: 10px 0;
}
.message-box.req-box {
  justify-content: flex-end;
}
.message-box.res-box {
  justify-content: flex-start;
}

/* 消息气泡 */
.req,
.res {
  max-width: 80%;
  min-height: 40px;
  padding: 12px 16px;
  border-radius: 12px;
  line-height: 1.5;
  font-size: 14px;
  word-wrap: break-word;
}

.req {
  background-color: #1475fb;
  color: white;
  border-bottom-right-radius: 4px;
}

.res {
  color: #333;
  border-bottom-left-radius: 4px;
}

/* 资源推荐 */
.recommend-box {
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
  align-items: center;
  height: 50px;
  width: 500px;
  background-color: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin: 15px 0;
}
.recommend-box:hover {
  box-shadow: 0 0 20px 8px #e1eeff;
}
.recommend-img {
  margin-right: 10px;
  width: 58px;
  height: 40px;
  background-image: url('@/assets/images/AI/assistant/资源推荐.png');
  background-position: center center;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

/* 开启新对话按钮 */
.open-new-box {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: -40px;
  padding: 3px 10px;
  width: 110px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  font-size: 12px;
  border-radius: 12px;
  color: #6da7f2;
  cursor: pointer;
  transition: all 0.3s ease;
}
.open-new-box:hover {
  background-color: #4fa1fb;
  color: white;
}
.open-new-box:hover #img1 {
  display: none;
}
.open-new-box:hover #img2 {
  width: 20px;
  height: 20px;
}

/* 输入框容器 */
.input-box {
  position: absolute;
  bottom: -120px;
  width: 100%;
  padding: 10px;
  border-radius: 10px;
  border: 2px solid #aed0fc;
  background-color: white;
  margin-top: 6px;
}
.input-box textarea {
  width: 100%;
  min-height: 50px;
  max-height: 150px;
  padding: 10px;
  font-size: 14px;
  color: #333;
  border: none;
  outline: none;
  resize: none;
  box-sizing: border-box;
  overflow-y: auto;
  background-color: transparent;
  line-height: 1.5;
}
.robot-box {
  width: 160px;
  height: 145px;
  position: absolute;
  bottom: 50px;
  right: -100px;
  background: url('@/assets/images/home/AI.png') center center / cover no-repeat;
  z-index: 1000;
  cursor: pointer;
  transition: all 0.5s ease;
}
.hidden {
  bottom: 120px;
  right: 0;
  width: 0;
  height: 0;
}
</style>